﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace SHFST.Core
{
   class Animation
   {
      // 15 fps
      const int FPS = 66;
      int frameStart = 0;
      public Point frameSize;
      Point currentFrame = new Point (0, 0);
      Point sheetSize;
      public Texture2D sprite;

      public void Load (Texture2D newSprite, Point newFrameSize, Point newSheetSize)
      {
         sprite = newSprite;
         frameSize = newFrameSize;
         sheetSize = newSheetSize;
      }

      public void Update (int elapsedTime)
      {
         frameStart += elapsedTime; //starting from 0, increment frame start at the speed of milliseconds
         if (frameStart > FPS) //when framstart goes above the max fps (30)
         {
            frameStart -= FPS;

            ++currentFrame.X; // move the source rectangle 1 frame to the right
            if (currentFrame.X >= sheetSize.X)
            {
               currentFrame.X = 0; //once the source rectangle moves 4 spaces to the right, reset to the first column
               ++currentFrame.Y; //move the source rectangle down one
               if (currentFrame.Y >= sheetSize.Y)
               {
                  currentFrame.Y = 0; //when at the bottom of the sheet reset the source to the top
               }
            }
         }
      }

      public void Draw (SpriteBatch batch, Point position)
      {
         batch.Draw (sprite,
                     new Vector2 (position.X, position.Y),
                     new Rectangle (currentFrame.X * frameSize.X, //first point starts at 0, 0
                                    currentFrame.Y * frameSize.Y, //second at 0, 0
                                    frameSize.X, //third, 128, 0
                                    frameSize.Y), // fourth, 0,128
                     Color.White);
      }

      public void GetData (Color[] colorArray)
      {
         sprite.GetData <Color> (0,
                                 new Rectangle (currentFrame.X * frameSize.X, //first point starts at 0, 0
                                                currentFrame.Y * frameSize.Y, //second at 0, 0
                                                frameSize.X, //third, 128, 0
                                                frameSize.Y), // fourth, 0,128
                                 colorArray,
                                 0,
                                 frameSize.X * frameSize.Y);
      }
   }
}
